﻿using ADSTS_SERVER.VO.Cluster;
using AngleSharp.Common;
using Furion.RemoteRequest.Extensions;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System.Linq;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace ADSTS_SERVER.Controllers
{
    /// <summary>
    /// 集群接口
    /// </summary>
    [DynamicApiController]
    public class ClusterController
    {
        private readonly ILogger<ClusterController> logger;
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        private readonly IMemoryCache memoryCache;
        public ClusterController(ISqlSugarClient db, ILogger<ClusterController> logger, IMemoryCache memoryCache)
        {
            this.db = db;
            this.logger = logger;
            this.memoryCache = memoryCache;
        }

        /// <summary>
        /// 列表接口
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> List(ListVO vo)
        {
            int statusCode = 0;
            bool succeeded = false;

            string result = await "#(API:DATA)/cluster/list".SetBody(vo).PostAsStringAsync();
            JObject data = JObject.Parse(result);
            if ((bool)data["succeeded"] is true)
            {
                statusCode = 1;
                succeeded = true;
            }

            // 查看所有在线mac地址信息
            string onlineClientStr = await "#(API:DATA)/cluster/onlineClient".PostAsStringAsync();
            JObject onlineClient = JObject.Parse(onlineClientStr);
            List<string> onlineMacs = onlineClient["data"].ToObject<List<string>>();

            foreach (var item in data["data"].ToList())
            {
                foreach (var client in item["clients"])
                {
                    if (onlineMacs.Contains(client["mac"].ToString()))
                    {
                        client["status"] = 1;
                    }
                    else
                    {
                        client["status"] = 0;
                    }
                }
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = statusCode,
                Succeeded = succeeded,
                Data = data["data"],
                Errors = data["errors"],
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 添加接口
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Save(List<SaveVO> vo)
        {
            int statusCode = 0;
            bool succeeded = false;

            string result = await "#(API:DATA)/cluster/save".SetBody(vo).PostAsStringAsync();
            JObject data = JObject.Parse(result);
            if ((bool)data["succeeded"] is true)
            {
                statusCode = 1;
                succeeded = true;
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = statusCode,
                Succeeded = succeeded,
                Data = data["data"],
                Errors = data["errors"],
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Delete(List<long> vo)
        {
            int statusCode = 0;
            bool succeeded = false;

            string result = await "#(API:DATA)/cluster/delete".SetBody(vo).PostAsStringAsync();
            JObject data = JObject.Parse(result);
            if ((bool)data["succeeded"] is true)
            {
                statusCode = 1;
                succeeded = true;
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = statusCode,
                Succeeded = succeeded,
                Data = data["data"],
                Errors = data["errors"],
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Update(UpdateVO vo)
        {
            int statusCode = 0;
            bool succeeded = false;
            string errors = "";

            string result = await "#(API:DATA)/cluster/update".SetBody(vo).PostAsStringAsync();
            JObject data = JObject.Parse(result);
            if ((bool)data["succeeded"] is true)
            {
                statusCode = 1;
                succeeded = true;
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = statusCode,
                Succeeded = succeeded,
                Data = data["data"],
                Errors = data["errors"],
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 查看接口
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Show(ShowVO vo)
        {
            int statusCode = 0;
            bool succeeded = false;
            string errors = "";

            string result = await "#(API:DATA)/cluster/show".SetBody(vo).PostAsStringAsync();
            JObject data = JObject.Parse(result);
            if ((bool)data["succeeded"] is true) {
                statusCode = 1;
                succeeded = true;
            }

            // 查看所有在线mac地址信息
            string onlineClientStr = await "#(API:DATA)/cluster/onlineClient".PostAsStringAsync();
            JObject onlineClient = JObject.Parse(onlineClientStr);
            List<string> onlineMacs = onlineClient["data"].ToObject<List<string>>();

            foreach (var item in data["data"]["clients"].ToList())
            {
                if (onlineMacs.Contains(item["mac"].ToString()))
                {
                    item["status"] = 1;
                }
                else
                {
                    item["status"] = 0;
                }
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = statusCode,
                Succeeded = succeeded,
                Data = data["data"],
                Errors = data["errors"],
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// Unity端集群登录时连接接口
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Connection(ConnectionVO vo)
        {
            memoryCache.Remove(vo.LinkToken);
            memoryCache.Set(vo.LinkToken, vo);

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 1,
                Succeeded = true,
                Data = vo,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// web端根据LinkToken获取本机信息接口
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> LinkTokenInfo(LinkTokenInfoVO vo)
        {
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 1,
                Succeeded = true,
                Data = memoryCache.Get(vo.LinkToken),
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// web端获取该用户仿真客户端的信息是否在自己的集群中接口
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> IsInCluster(IsInClusterVO vo)
        {
            int statusCode = 0;
            bool succeeded = false;

            string result = await "#(API:DATA)/cluster/userClient".SetBody(vo).PostAsStringAsync();
            JObject data = JObject.Parse(result);
            if ((bool)data["succeeded"] is true)
            {
                statusCode = 1;
                succeeded = true;
            }
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = statusCode,
                Succeeded = succeeded,
                Data = data["data"],
                Errors = data["errors"],
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// web端针对工程下所属集群发送信息接口
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> SendMsg(SendMsgVO vo)
        {
            int statusCode = 0;
            bool succeeded = false;

            // 根据项目ID查看项目信息
            string projectStr = await "#(API:DATA)/project/show".SetBody(vo).PostAsStringAsync();
            JObject project = JObject.Parse(projectStr);

            // 根据项目中集群ID查看集群信息
            string clusterStr = await "#(API:DATA)/cluster/show".SetBody(new
            {
                Id = (long)project["data"]["cluId"]
            }).PostAsStringAsync();
            JObject cluster = JObject.Parse(clusterStr);
            List<string> macs = cluster["data"]["clients"].Select(client => (string)client["MacAddress"]).ToList();

            // 查看所有在线mac地址信息
            string onlineClientStr = await "#(API:DATA)/cluster/onlineClient".PostAsStringAsync();
            JObject onlineClient = JObject.Parse(onlineClientStr);
            List<string> onlineMacs = onlineClient["data"].ToObject<List<string>>();

            // 如果该项目所属集群所有机器都在线
            if (macs.All(m => onlineMacs.Contains(m)))
            {
                string result = await "#(API:DATA)/project/sendMessage".SetBody(vo).PostAsStringAsync();
                JObject data = JObject.Parse(result);
                if ((bool)data["succeeded"] is true)
                {
                    statusCode = 1;
                    succeeded = true;
                }
            }

            //UnifyContext.Fill(new { Macs = macs, OnlineClient = onlineClient["data"] });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = statusCode,
                Succeeded = succeeded,
                Data = null,
                Errors = onlineClient["errors"],
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
